_sys:addPath('res')

Teapot = {}
Teapot.__index = Teapot
function Teapot:new()
	local o = {}
	setmetatable(o, Teapot)
	o.mesh = _mf:createTeapot()
	o.oldPosition = _Vector3.new(0, 0, 0)
	o.newPosition = _Vector3.new(0, 0, 5)
	o.oldDirection = _Vector3.new(-1, 0, 0)
	o.newDirection = _Vector3.new(0, 0, 0)
	o.v = _Vector3.new(0, 0, 0)
	return o
end

function Teapot:addToScene(sen)
	self.newHeight = sen.terrain:getHeight(0, 0) + 3
	self.mesh.transform:setScaling(3, 3, 3)
	self.mesh.transform:mulTranslationRight(0, 0, 3)
	self.node = sen:add(self.mesh)
end

function Teapot:move(e, sen)
	self.oldPosition:set(self.mesh.transform:getTranslation())
	if self.oldPosition:equal(self.newPosition) then
		return
	end
	self.v = _Vector3.sub(self.newPosition, self.oldPosition)
	if self.v:magnitude() > 0.1 * e then
		self.v = self.v:scale(0.1 * e)
	end
	self.mesh.transform:mulTranslationRight(self.v)
end

function Teapot:changeDirection()
	self.newDirection:set(_Vector3.sub(self.newPosition, self.oldPosition))
	self.newDirection.z = 0
	self.mesh.transform:mulFaceToLeft(self.oldDirection, self.newDirection, 200)
	self.oldDirection:set(self.newDirection)
end

local sen = _Scene.new('terrain.sen')
local teapot = Teapot.new()
teapot:addToScene(sen)

font = _Font.new('Aril', 10)
font.textColor = _Color.Yellow

local function mouse(button, x, y)
	if button == 0 then
		local result = sen:pick(_rd:buildRay(x, y))
		if result.x == teapot.oldPosition.x and result.y == teapot.oldPosition.y then
			return
		end
		teapot.newPosition:set(result.x, result.y, sen.terrain:getHeight(result.x, result.y) + 3)
		teapot:changeDirection()
	end
end

local function render(e)
	font:drawText(0, 0, 'Press MouseLeft to draw orbit')
	teapot:move(e, sen)
	sen:render()
end

_app:onIdle(render)
_app:onMouseDown(mouse)